#!/usr/bin/env groovy

def call(Map config = [:]) {

//    def podTemplate = utilities.pod_template()
    pipeline {
        agent {
            label "jenkins-maven"
        }
        parameters {
            choice(name: 'deployEnv', choices: ['dev','demo'])
            string(name: 'versionNum', description: '构建版本号')
            string(name: 'projectCode', description: '项目编码')
        }
        environment {
            //ORG为整体项目名称，例示：klx为产品项目
            //ORG               = "${config.project.code}"
            //APP_NAME为该项目的的名称，也为镜像的名称
            //APP_NAME          = "${config.project.appName}"
            ORG = "klx"
            CHARTMUSEUM_CREDS = credentials('chartmuseum')
            PREVIEW_NAMESPACE = "preview"
            TEST_NAMESPACE = "test"
            DEV_NAMESPACE = "dev"
            BUG_NAMESPACE = "bug"
            DEMO_NAMESPACE = "demo"
            buildVersion = " "
            spaces = ' '
            test404 = ' '
        }
        stages {
            stage('获取相关代码'){
                environment {
//                    projectpom = readMavenPom file: 'pom.xml'
//                    projectArtifactId = projectpom.getArtifactId()
//                    Artifact_ID  = "${projectArtifactId}"
                    K8S_persistence_enabled  = "false"
                    K8S_env_appParams = "--server.port=80 --spring.profiles.active=$deployEnv"
                    K8S_env_javaParams = "-Xmx512m"
                }
                steps{
                    container('maven') {
                        checkFromGit('./k8sconfig','git@gitee.com:klxedu/k8sconfig-java.git','PR-1')
                        dir ('./k8sconfig') {
                            script{
                                env.Artifact_ID = projectCode
                                K8S_health_path="actuator/health"
                                sh "mv charts/ARTIFACT_ID charts/${ARTIFACT_ID}"
                                sh "export K8S_health_path='${K8S_health_path}' && \
                                    make replace"
                            }
                        }
                    }
                }
            }
            stage('deploy') {
                steps {
                    container('maven') {
                        script {
                            try {
                                dir ("./k8sconfig/charts/$deployEnv") {
                                    container('maven') {
                                        env.PREVIEW_VERSION = "0.0.0-SNAPSHOT"
                                        env.IMAGE_VERSION = versionNum
                                        sh "export FILE_NAME=$projectCode && export NAMESPACE=$deployEnv && make preview"

                                        sh "helm template -n $deployEnv --output-dir . . "
                                        sh "kubectl apply -f ./$deployEnv/charts/$projectCode/templates/ -n $deployEnv "
                                        //删除容器重新加载新部署的镜像
                                        sh "kubectl get pod -n $deployEnv  |grep $projectCode | awk '{print \$1}'|xargs -I {} kubectl delete pod -n $deployEnv  {} --force --grace-period=0"
                                        sh "chown -R 10000:10000 ../$deployEnv"
                                    }
                                }
                            } catch (Exception e) {
                                error('Stopping early…')
                            }
                        }
                    }
                }
            }
        }
        post {
            always {
                input """Pipeline debug.
                    Select Proceed or Abort to terminate the build pod"""
                cleanWs()
            }
        }
    }
}

def checkFromGit(dir,url,branches){
    checkout([$class: 'GitSCM', branches: [[name: branches]], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: dir]], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'gitee-admin', url: url]]])
}